package classLoader;

import javax.print.attribute.standard.PrinterURI;
import java.io.*;
import java.security.PrivateKey;

/**
 * 自定义类加载器，用于加载webapps下的web应用
 */
public class CatClassLoader extends ClassLoader{

    public CatClassLoader( String classpath) {
        this.classpath = classpath;
    }

    //类路径
    private String classpath;

    public String getClasspath() {
        return classpath;
    }

    public void setClasspath(String classpath) {
        this.classpath = classpath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            //获得byte数组
            byte[] byteData = getByteData(name);
            if (byteData!=null){
                //将字节码文件转换为Class对象
                return super.defineClass(name,byteData,0,byteData.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    /**
     * 获取字节码
     * @param className
     * @return
     * @throws Exception
     */
    private byte[] getByteData(String className) throws Exception{
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        //全路径
        String path = classpath + File.separator+className.replace(".",File.separator)+".class";
        try {
            in = new FileInputStream(path);
             out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024 * 8];
            int len = 0;
            while ((len=in.read(bytes))!=-1){
                out.write(bytes,0,len);
            }
            out.flush();
            return out.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
        return null;
    }
}
